package com.vm.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.vm.adapter.RememberPsdAdapter;
import com.vm.commons.CurrentUser;
import com.vm.commons.VMConst;
import com.vm.db.LocalUserInfoDao;
import com.vm.db.RememberPsdDao;
import com.vm.model.LocalUserInfo;
import com.vm.model.RememberPsd;
import com.vm.model.UserInfo;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月12日 下午6:34:00]
 * @Version: [v1.0]
 * 
 */
public class LoginActivity extends Activity {

	static final String TAG = "LoginActivity";
	TextView tv_register;
	EditText et_account_name;
	EditText et_account_password;
	Button btn_account_login;
	RelativeLayout rl_login;
	TextView tv_forget_password;
	private RequestQueue mQueue;
	private LocalUserInfoDao luidao = null;
	private RememberPsdDao rDao = null;
	ImageView imgbtn_search_back;
	CheckBox checkbox;
	public static Handler mainHandler;
	private List<RememberPsd> list;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		luidao = new LocalUserInfoDao(LoginActivity.this);
		rDao = new RememberPsdDao(LoginActivity.this);
		mQueue = MyVolley.getRequestQueue();
		init();

	}

	public void init() {
		rl_login = (RelativeLayout) findViewById(R.id.rl_login);
		rl_login.setOnClickListener(new OnClickListener() {
			final ListView lv_rememberpsd = (ListView) findViewById(R.id.lv_rememberpsd);

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (lv_rememberpsd.getVisibility() == View.VISIBLE) {
					lv_rememberpsd.setVisibility(View.GONE);
				}
			}
		});
		tv_forget_password = (TextView) findViewById(R.id.tv_forget_password);
		tv_forget_password.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(LoginActivity.this,
						ForgetPsdActivity.class);
				startActivity(intent);
			}
		});
		tv_register = (TextView) findViewById(R.id.tv_register);
		tv_register.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(LoginActivity.this,
						RegisterActivity.class);
				startActivity(intent);
			}
		});
		et_account_name = (EditText) findViewById(R.id.et_account_name);
		et_account_name.setOnClickListener(remember_listener);
		et_account_name.setFocusable(true);
		et_account_name.setFocusableInTouchMode(true);
		et_account_name.requestFocus();
		et_account_password = (EditText) findViewById(R.id.et_account_password);
		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
		checkbox = (CheckBox) findViewById(R.id.checkbox);
		btn_account_login = (Button) findViewById(R.id.btn_account_login);
		btn_account_login.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String username = et_account_name.getText().toString();
				String password = et_account_password.getText().toString();

				if (!username.equals("") && !password.equals("")) {
					
					try {
						username = URLEncoder.encode(username, "UTF-8");
					} catch (UnsupportedEncodingException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					String url = VMConst.LOGINREQUEST + "?username=" + username
							+ "&password=" + password;

					StringRequest stringRequest;
					try {
						stringRequest = new StringRequest(url,
								new Listener<String>() {

									@Override
									public void onResponse(String arg0) {
										// TODO Auto-generated method stub
										Gson gson = new Gson();

										UserInfo userInfo = gson.fromJson(arg0,
												UserInfo.class);
										if (userInfo != null) {
											try {
												Toast toast = Toast.makeText(
														LoginActivity.this,
														"登录成功",
														Toast.LENGTH_SHORT);
												toast.show();
												RememberPsd rememberPsd = new RememberPsd();
												LocalUserInfo localUserInfo = new LocalUserInfo();
												localUserInfo
														.setUserId(userInfo
																.getId());
												localUserInfo
														.setUsername(userInfo
																.getName());
												localUserInfo.setIntergral(userInfo
														.getIntegrity());
												localUserInfo
														.setImageUrl(userInfo
																.getIcon());
												localUserInfo.setPsd(userInfo
														.getPwd());
												localUserInfo
														.setNickname(userInfo
																.getNickName());
												localUserInfo.setPhone(userInfo
														.getMobilephone());
												localUserInfo.setInvCode(userInfo
														.getPromoterName());
												// localUserInfo.set
												luidao.insert(localUserInfo);
												CurrentUser.USERPSD = userInfo
														.getPwd();
												CurrentUser.USERID = userInfo
														.getId();
												CurrentUser.USERNAME = userInfo
														.getName();
												CurrentUser.NICKNAME = userInfo
														.getNickName();
												CurrentUser.PHONNE = userInfo
														.getMobilephone();
												if (userInfo.getPromoterName() != null) {
													// 邀请码
													CurrentUser.INVCODE = userInfo
															.getPromoterName();
												}

												if (userInfo.getIntegrity() != null) {
													CurrentUser.INTERGRAL = userInfo
															.getIntegrity();
												}
												if (userInfo.getIcon() != null) {
													CurrentUser.IMAGEURL = userInfo
															.getIcon();
												}
												if (checkbox.isChecked() == true) {

													if (rDao.ifExits(userInfo
															.getId()) == true) {
														rememberPsd
																.setUserId(userInfo
																		.getId());
														rememberPsd
																.setPsd(userInfo
																		.getPwd());
														rememberPsd
																.setUsername(userInfo
																		.getName());
														rDao.update(rememberPsd);
													} else {
														rememberPsd
																.setPsd(userInfo
																		.getPwd());
														rememberPsd
																.setUsername(userInfo
																		.getName());
														rememberPsd
																.setUserId(userInfo
																		.getId());
														rDao.insert(rememberPsd);
													}
												} else {

												}
												// Intent intent = new Intent(
												// LoginActivity.this,
												// MainTabActivity.class);
												// LoginActivity.this
												// .startActivity(intent);
												//
												// Message message = new
												// Message();
												// message.what = 100;
												// mainHandler
												// .sendMessage(message);
												onBackPressed();
												LoginActivity.this.finish();

											} catch (Exception e) {
												// TODO Auto-generated catch
												// block
												Log.e(TAG, e.getMessage());
											}
										}
									}
								}, new Response.ErrorListener() {
									@Override
									public void onErrorResponse(
											VolleyError error) {
										Toast toast = Toast.makeText(
												LoginActivity.this, "用户名或密码错误",
												Toast.LENGTH_SHORT);
										toast.show();
									}

								});
						mQueue.add(stringRequest);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						Log.e(TAG, e.getMessage());
					}

				} else {
					Toast toast = Toast.makeText(LoginActivity.this,
							"用户名或密码不能为空", Toast.LENGTH_SHORT);
					toast.show();
				}

			}
		});
	}

	OnClickListener remember_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final ListView lv_rememberpsd = (ListView) findViewById(R.id.lv_rememberpsd);
			if (lv_rememberpsd.getVisibility() == View.GONE) {
				list = rDao.selectall();
				if (list.size() > 0 || list != null) {
					lv_rememberpsd.setVisibility(View.VISIBLE);
					RememberPsdAdapter adapter = new RememberPsdAdapter(
							LoginActivity.this, list);
					lv_rememberpsd.setAdapter(adapter);
					lv_rememberpsd.setOnItemClickListener(list_listener);
				}
			} else {
				lv_rememberpsd.setVisibility(View.GONE);
			}
		}

	};
	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	OnItemClickListener list_listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			ListView lv_rememberpsd = (ListView) findViewById(R.id.lv_rememberpsd);
			TextView tv_username = (TextView) view
					.findViewById(R.id.tv_username);
			Object object = tv_username.getTag();
			if (object != null) {
				RememberPsd rememberpsd = (RememberPsd) object;
				et_account_name.setText(rememberpsd.getUsername());
				et_account_password.setText(rememberpsd.getPsd());
				lv_rememberpsd.setVisibility(View.GONE);
			}
		}
	};
}
